import React, {Component} from 'react'
import './ShowTreeToast.less'
import {Con, Row, Col, Panel, Button, FormControl, Icon, Modal} from 'tinper-bee'
import Tree from 'bee-tree';
import {searchWorkProList} from '../WorkType/worktype.config'
import {vendorsDanger as danger,vendorsTrimStr as trimStr} from '../../utils/config'
import TopTreeNode from "./TopTreeNode.jsx";
import App from "../../layout/App";
const TreeNode = Tree.TreeNode;
const dataList = [];
const generateList = (data) => {
    for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const key = node.key;
        const scode = node.scode;
        dataList.push({
            key:node.pkProcedure,
            title: key,
            scode:scode
        });
        if (node.children) {
            generateList(node.children, node.key);
        }
    }
};
const getParentKey = (key,scode, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        const scode=node.scode;
        if (node.children) {
            if (node.children.some(item => item.pkProcedure === key)||node.children.some(item => item.scode === scode)) {
                parentKey = node.pkProcedure;
            } else if (getParentKey(key,scode, node.children)) {
                parentKey = getParentKey(key,scode, node.children);
            }
        }
    }
    return parentKey;
};
export default class ShowTreeToast extends Component {
    constructor(props) {
        super(props);
        this.state = {
            errToast: false,
            selectedKeys: [],
            dangerToast:false,
            qualitySearchValue: '',
            pkProcedure:'',
            gData: [],
            flagColor:'',
            expandedKeys: [],
            searchValue: '',
            autoExpandParent: true,
        };
        this.lastData = [];
    }
    componentDidMount() {
        searchWorkProList({isAjax:1,ieStamp:new Date().getTime()}).then((res) => {
            if (res.data.resultCode != 'busi_ex') {
                let gData=this.getData(res.data.result);
                this.setState({gData}, () => {
                    this.getLastData(this.state.gData);
                    generateList(this.state.gData);
                    this.allExpand();
                })
            } else {
                danger({'text': res.data.exMsg})
            }
        });
    }
    getData=(data)=>{
        let gData=[];
        for (let i = 0; i < data.length; i++) {
            let oneItem = data[i];
            let gDataItem={};
            gDataItem['key']=oneItem.sname;
            gDataItem['title']=oneItem.sname;
            gDataItem['pkProcedure']=oneItem.pkProcedure;
            gDataItem['scode']=oneItem.scode;
            gDataItem['changeColor']='';
            if (oneItem['childProcedure']){
                gDataItem['children']=this.getData(oneItem.childProcedure);
                gData.push(gDataItem);
            }else {
                gData.push(gDataItem);
            }
        }
        return gData
    };
    getLastData = (data) => {
        for (let i = 0; i < data.length; i++) {
            let item = data[i];
            if (item['children']) {
                this.getLastData(item['children'])
            } else {
                this.lastData.push(item)
            }
        }
    };
    handleClick = () => {
        let dangerToast=0;
        let data = this.state.gData;
        let selectedLastKeys = this.state.selectedKeys;
        selectedLastKeys = selectedLastKeys[0];
        let lastData = this.lastData;
        for (let i = 0; i < lastData.length; i++) {
            let item = lastData[i];
            if (item.pkProcedure == selectedLastKeys) {
                this.props.onToastSearch(item.key,item.pkProcedure);
            }
        }
        for (let i = 0; i < lastData.length; i++) {
            let item = lastData[i];
            if (selectedLastKeys !== item.pkProcedure) {
                dangerToast = dangerToast + 1
            }
        }
        if (dangerToast == lastData.length) {
            danger({'text': '请选择末级工序'});
        }
    };
    getPkProcedure=()=>{
        let lastKey=this.state.selectedKeys;
        lastKey=lastKey[0];
        let chooseItem=this.state.gData;
        for (let i = 0; i < chooseItem.length; i++) {
            let item = chooseItem[i];
            if (item.pkProcedure===lastKey){
                this.setState({pkProcedure:item.pkProcedure});
                break
            }else {
                if (item['children']){
                    let secondChooseItem=item['children'];
                    for (let j = 0; j < secondChooseItem.length; j++) {
                        let item = secondChooseItem[j];
                        if (item.pkProcedure===lastKey){
                            this.setState({pkProcedure:item.pkProcedure});
                            break
                        }else {
                            if (item['children']){
                                let threeChooseItem=item['children'];
                                for (let k = 0; k < threeChooseItem.length; k++) {
                                    let item = threeChooseItem[k];
                                    if (item.pkProcedure===lastKey){
                                        this.setState({pkProcedure:item.pkProcedure});
                                        break
                                    }else{
                                        if (item['children']){
                                            let fourChooseItem=item['children'];
                                            for (let k = 0; k < fourChooseItem.length; k++) {
                                                let item = fourChooseItem[k];
                                                if (item.pkProcedure===lastKey){
                                                    this.setState({pkProcedure:item.pkProcedure});
                                                    break
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    };
    onExpand = (expandedKeys, {expanded: bool, node}) => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    };
    handleSelect = (selectedKeys, {selected: bool, selectedNodes, node, event}) => {
        if (selectedKeys.length){
            this.getNullColor(this.state.gData)
        }
        this.setState({selectedKeys},()=>{
            let selectedLastKeys = this.state.selectedKeys;
            selectedLastKeys = selectedLastKeys[0];
            let lastData = this.lastData;
            for (let i = 0; i < lastData.length; i++) {
                let item = lastData[i];
                if (item.key == selectedLastKeys) {
                    this.getPkProcedure();
                    break
                }
            }
        })
    };
    handleSearchClick = () => {
        let dangerToast=0;
        let gData=this.state.gData;
        let value=this.state.searchValue;
        let reg=/([^\s]+)/g;
        let arr=[];
        const chooseArr=[];
        this.changeColor(chooseArr,gData);
        value=trimStr(value);
        value.replace(reg,function () {
            arr.push(arguments[0])
        });
        if (value) {
            for (let i = 0; i < dataList.length; i++) {
                let item = dataList[i];
                let keyTotal=0;
                let scodeTotal=0;
                for (let i = 0; i < arr.length; i++) {
                    let arrItem = arr[i];
                    if (item.title.indexOf(arrItem)>-1){
                        keyTotal+=1;
                    }
                    if (item.scode.indexOf(arrItem)>-1){
                        scodeTotal+=1
                    }
                }
                if (keyTotal===arr.length||scodeTotal===arr.length) {
                    chooseArr.push(item);
                }
            }
            this.getNullColor(gData);
            this.allExpand();
            this.changeColor(chooseArr,gData);
            this.setState({gData});
            if (!chooseArr.length){
                danger({'text': '没有找到符合的信息!'});
            }
        } else {
            danger({'text': '请输入具体内容!'});
        }

    };
    getNullColor=(gData)=>{
        for (let i = 0; i < gData.length; i++) {
            let item = gData[i];
            if(item['children']){
                item['changeColor']='';
                this.getNullColor(item['children'])
            }else {
                item['changeColor']=''
            }
        }
    };
    changeColor=(chooseArr,gData)=>{
        for (let i = 0; i < chooseArr.length; i++) {
            let item = chooseArr[i];
            let itemKey=item.key;
            for (let j = 0; j < gData.length; j++) {
                let  gDataItem= gData[j];
                let  gDataKey=gDataItem.pkProcedure;
                if (gDataItem.children){
                    if (itemKey===gDataKey){
                        gDataItem['changeColor']='back_color';
                    }
                    this.changeColor(chooseArr,gDataItem.children)
                }else {
                    if (itemKey===gDataKey){
                        gDataItem['changeColor']='back_color';
                    }
                }
            }
        }
    };
    allExpand=()=>{
        let value=this.state.searchValue;
        const expandedKeys = [];
        dataList.forEach((item) => {
            expandedKeys.push(getParentKey(item.key,item.scode,this.state.gData));
        });
        this.setState({
            expandedKeys: expandedKeys,
            autoExpandParent: true,
        });
    };
    onChange = (e) => {
        let value = e.target.value;
        this.setState({
            searchValue: value,
        });
    };
    handleFocus=()=>{
        this.setState({focusColor:'focus_color'})
    };
    handleBlur=()=>{
        this.setState({focusColor:''})
    };
    render() {
        const {
            searchValue,
            expandedKeys,
            autoExpandParent
        } = this.state;
        const loop = data => data.map((item) => {
            if (item.children){
                return (
                    <TreeNode key={item.pkProcedure}  title={<TopTreeNode changeColor={item.changeColor} title1={item.scode} title={item.key}/>}>
                        {loop(item.children)}
                    </TreeNode>
                )
            }
            return <TreeNode key={item.pkProcedure} title={<TopTreeNode changeColor={item.changeColor} title1={item.scode} title={item.key}/>}/>;
        });
        return (
            <App>
                <div>
                    <Modal show={this.props.showModal} className='tree-containers'>
                        <div className='modal_content'>
                            <Modal.Header>
                                <span className="chooseproduct">选择工序</span>
                                <Icon
                                    onClick={()=>{
                                        this.props.close();
                                        this.getNullColor(this.state.gData);
                                        this.allExpand()
                                    }}
                                    type="uf-close-bold"
                                    style={{float: 'right', 'font-size': '12px', color: 'rgba(93,93,93,1)'}}/>
                                <div className='div_after'></div>
                            </Modal.Header>
                            <div className='Modal_Body'>
                                <Modal.Body>
                                    <div className='center_top'>
                                        <FormControl placeholder='请输入工序编码、工序名称'
                                                     className='search_form'
                                                     onChange={this.onChange}
                                                     onFocus={this.handleFocus}
                                                     onBlur={this.handleBlur}
                                        />
                                        <Button className={"font-btnsize "+this.state.focusColor} onClick={this.handleSearchClick}>搜索</Button>
                                    </div>
                                    <div className='center_bottom'>
                                        <Tree
                                            openIcon={<Icon type="uf-reduce-s"/>}
                                            closeIcon={<Icon type="uf-add-s"/>}
                                            onExpand={this.onExpand}
                                            onSelect={this.handleSelect}
                                            expandedKeys={expandedKeys}
                                            autoExpandParent={autoExpandParent}>
                                            {loop(this.state.gData)}
                                        </Tree>
                                    </div>
                                </Modal.Body>
                            </div>
                            <Modal.Footer>
                                <div className="btn-group">
                                    <Button className='btn font-btnsize mg-top' onClick={()=>{
                                        this.props.close();
                                        this.getNullColor(this.state.gData);
                                        this.allExpand()
                                    }}>取消</Button>
                                    <Button className='btn btn_right font-btnsize mg-top' colors="primary" onClick={this.handleClick}>确定</Button>
                                </div>

                            </Modal.Footer>
                        </div>
                    </Modal>
                </div>
            </App>
        )
    }
}
